<template>
    <div v-loading="loading">
        <h2>{{ assignInfo?.title }}</h2>
        <div class="activity-dates">
            <p class="date-p">
                <strong>{{ $t('mod.assign.report.date_1') }}</strong
                >{{ assignInfo?.start_date ? formatLoginTime(assignInfo.start_date) : '' }}
            </p>
            <p class="date-p">
                <strong>{{ $t('mod.assign.report.date_2') }}</strong
                >{{ assignInfo?.end_date ? formatLoginTime(assignInfo.end_date) : '' }}
            </p>
        </div>
        <div class="tag-list">
            <el-tag color="#6C757D" effect="dark" v-if="roleStore.isTeacher">{{ $t('mod.assign.report.con_1') }}</el-tag>
        </div>
        <el-form label-width="auto" class="search-form">
            <el-form-item :label="$t('mod.assign.report.search_form.label')" size="large">
                <el-select v-model="type" :placeholder="$t('mod.assign.report.search_form.placeholder')">
                    <el-option :label="$t('mod.assign.report.search_form.opt_1')" :value="1" />
                    <el-option :label="$t('mod.assign.report.search_form.opt_2')" :value="2" />
                    <el-option :label="$t('mod.assign.report.search_form.opt_3')" :value="3" />
                    <el-option :label="$t('mod.assign.report.search_form.opt_4')" :value="4" />
                    <el-option :label="$t('mod.assign.report.search_form.opt_5')" :value="5" />
                </el-select>
            </el-form-item>
            <div class="btn-list">
                <el-button color="#435764" @click="resetFilter">{{ $t('mod.assign.report.search_form.btn_text_1') }}</el-button>
                <el-button color="#F06423" @click="getAssignReportList">{{ $t('mod.assign.report.search_form.btn_text_2') }}</el-button>
            </div>
        </el-form>
        <QuickFilter @filter-change="handleFilterChange" />
        <div class="btn-list justify-end" v-if="checkedReport.length">
            <el-button color="#F06423" @click="backDraftHandle([])">{{ $t('mod.assign.report.btn_text_1') }}</el-button>
            <el-button color="#F06423" @click="lateDateHandle([])">{{ $t('mod.assign.report.btn_text_2') }}</el-button>
        </div>
        <el-table stripe border :data="assignReportList" style="width: 100%" v-if="assignReportList.length" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="40" />
            <el-table-column fixed sortable :label="$t('mod.assign.report.table_label_1')" width="200">
                <template #default="{ row }">
                    <div class="user-box" @click="goPage(`/console/user/${row.student_id}?courseId=${courseId}`)">
                        <div class="user-picture pic">
                            <img :src="row.avatar_url" class="ele" v-if="row.avatar_url" />
                            <el-icon size="20" color="#fff" v-else><User /></el-icon>
                        </div>
                        <div class="user-info">{{ row.last_name }} {{ row.first_name }}</div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="code" :label="$t('mod.assign.report.table_label_2')" width="160" />
            <el-table-column :label="$t('mod.assign.report.table_label_3')" width="160">
                <template #default="{ row }">{{ $t(statusText(row.submission_status)) }}</template>
            </el-table-column>
            <el-table-column :label="$t('mod.assign.report.table_label_4')" width="100">
                <template #default="{ row }">{{ row.overall_status === 1 ? $t('mod.assign.report.table_label_4_con_1') : $t('mod.assign.report.table_label_4_con_1') }}</template>
            </el-table-column>
            <el-table-column :label="$t('mod.assign.report.table_label_5')" width="220">
                <template #default="{ row }">{{ row.late_date ? formatLoginTime(row.late_date) : '-' }}</template>
            </el-table-column>
            <el-table-column :label="$t('mod.assign.report.table_label_6')" width="220">
                <template #default="{ row }">
                    <span v-html="row.teacher_comment"></span>
                </template>
            </el-table-column>
            <el-table-column prop="score" :label="$t('mod.assign.report.table_label_7')" width="120" />
            <el-table-column :label="$t('mod.assign.report.table_label_8')" width="140" fixed="right">
                <template #default="{ row }">
                    <div class="el-icon-list">
                        <el-icon size="14" color="#000" circle :title="$t('mod.assign.report.table_label_8_con_1')" v-if="row.score" @click="editScoreHandle([row])"><EditPen /></el-icon>
                        <el-icon size="14" color="#000" circle :title="$t('mod.assign.report.table_label_8_con_2')" @click="lateDateHandle([row])"><Clock /></el-icon>
                        <el-icon size="14" color="#000" circle :title="$t('mod.assign.report.table_label_8_con_3')" @click="backDraftHandle([row])" v-if="row.score"><Back /></el-icon>
                        <el-icon size="14" color="#000" circle :title="$t('mod.assign.report.table_label_8_con_4')" @click="viewFileHandle(row)" v-if="row.file_url"><Memo /></el-icon>
                        <el-icon size="14" color="#000" circle :title="$t('mod.assign.report.table_label_8_con_5')" @click="viewGradeHandle(row)" v-if="row.submission_status !== 5"><View /></el-icon>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <div class="pagination-box">
            <el-pagination
                background
                v-model:page-size="pagination.limit"
                v-model:current-page="pagination.page"
                layout="sizes, prev, pager, next"
                :total="pagination.total"
                :page-sizes="[10, 20, 50, 100]"
                class="mt-4"
                :hide-on-single-page="true"
                @size-change="getAssignReportList"
                @current-change="getAssignReportList"
            />
        </div>


        <!-- <el-pagination
            size="small"
            background
            v-model:page-size="pagination.limit"
            v-model:current-page="pagination.page"
            layout="sizes, prev, pager, next"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            class="mt-4"
            :hide-on-single-page="true"
            @size-change="getAssignReportList"
        /> -->
        <div class="btn-list">
            <!-- <el-button color="#F06423" @click="downloadHandle">下載{{ checkedReport.length ? '选中的繳交' : '全部的繳交' }}作業</el-button> -->
            <el-button color="#F06423" @click="downloadHandle" :loading="downloadLoading">{{ $t('mod.assign.report.btn_text_3') }}</el-button>
        </div>
    </div>

    <!-- 准许延期 -->
    <el-dialog v-model="lateDateDialog" :title="$t('mod.assign.report.late_date_dialog.tit')" width="500" class="mobile-dialog">
        <el-form :model="checkedReport" label-position="top">
            <el-form-item :label="$t('mod.assign.report.late_date_dialog.label_1')">
                <div class="user-box" v-for="report in checkedReport" @click="goPage(`/console/user/${report.student_id}?courseId=${courseId}`)">
                    <div class="user-picture pic">
                        <img :src="report.avatar_url" class="ele" v-if="report.avatar_url" />
                        <el-icon size="20" color="#fff" v-else><User /></el-icon>
                    </div>
                    <div class="user-info">{{ report.last_name }} {{ report.first_name }}</div>
                </div>
            </el-form-item>
            <el-form-item :label="$t('mod.assign.report.late_date_dialog.label_2')">
                <el-date-picker v-model="lateDate" type="datetime" :placeholder="$t('mod.assign.report.late_date_dialog.label_2_placeholder')" format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button color="#F06423" @click="lateDateSubmit" :loading="lateDateLoading">{{ $t('golbal.btn_text_1') }}</el-button>
            <el-button color="#435764" @click="lateDateDialog = false" :loading="lateDateLoading">{{ $t('golbal.btn_text_3') }}</el-button>
        </template>
    </el-dialog>

    <!-- 查看档案 -->
    <el-dialog v-model="viewDialog" :title="$t('mod.assign.report.view_dialog.tit')" width="500" class="mobile-dialog">
        <div class="file-upload-submission">
            <div class="file-time">
                <a :href="checkedReport[0].similarity_report_url" class="file-name">
                    <el-icon size="16" color="#4c4c4c"><Reading /></el-icon>
                    <span>{{ checkedReport[0].file_url.split('/').pop() }}</span>
                </a>
                <div class="file-up-time" v-if="checkedReport[0].submission_time">{{ formatLoginTime(checkedReport[0].submission_time) }}</div>
            </div>
            <h4>{{ $t('mod.assign.report.view_dialog.submission.tit') }}</h4>
            <table>
                <tbody>
                    <tr>
                        <td width="120">{{ $t('mod.assign.report.view_dialog.submission.table_label_1') }}</td>
                        <td>{{ checkedReport[0].similarity_status || '-' }}</td>
                    </tr>
                    <tr>
                        <td width="120">{{ $t('mod.assign.report.view_dialog.submission.table_label_2') }}</td>
                        <td>{{ checkedReport[0].similarity_percentage || '-' }}</td>
                    </tr>
                </tbody>
            </table>
            <p class="tips">*{{ $t('mod.assign.report.view_dialog.submission.tip') }}</p>
        </div>
    </el-dialog>

    <!-- 将作業回復為草稿 -->
    <el-dialog v-model="backDraftDialog" :title="$t('mod.assign.report.back_draft_dialog.tit')" width="500" class="mobile-dialog">
        <p>{{ $t('mod.assign.report.back_draft_dialog.con') }}</p>
        <template #footer>
            <el-button color="#F06423" @click="backDraftSubmit" :loading="backDraftLoading">{{ $t('golbal.btn_text_1') }}</el-button>
            <el-button color="#435764" @click="backDraftDialog = false" :loading="backDraftLoading">{{ $t('golbal.btn_text_3') }}</el-button>
        </template>
    </el-dialog>

    <!-- 修改评分 -->
    <el-dialog v-model="editScoreDialog" :title="$t('mod.assign.report.edit_score_dialog.tit')" width="500" class="mobile-dialog">
        <el-form :model="checkedReport[0]" label-position="top">
            <el-form-item :label="$t('mod.assign.report.edit_score_dialog.label_1')">
                <div class="user-box" @click="goPage(`/console/user/${checkedReport[0].student_id}?courseId=${courseId}`)">
                    <div class="user-picture pic">
                        <img :src="checkedReport[0].avatar_url" class="ele" v-if="checkedReport[0].avatar_url" />
                        <el-icon size="20" color="#fff" v-else><User /></el-icon>
                    </div>
                    <div class="user-info">
                        <div class="fullname">{{ checkedReport[0].last_name }} {{ checkedReport[0].first_name }}</div>
                        <div class="tools-comms">{{ $t('mod.assign.report.edit_score_dialog.label_1_placeholder') }}{{ checkedReport[0].score }}</div>
                    </div>
                </div>
            </el-form-item>
            <el-form-item :label="$t('mod.assign.report.edit_score_dialog.label_2')">
                <el-input type="number" v-model="editScore.score" :placeholder="$t('mod.assign.report.edit_score_dialog.label_2_placeholder')"></el-input>
            </el-form-item>
            <el-form-item :label="$t('mod.assign.report.edit_score_dialog.label_3')">
                <el-input type="textarea" v-model="editScore.teacher_comment" :placeholder="$t('mod.assign.report.edit_score_dialog.label_3_placeholder')" :rows="4"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button color="#F06423" @click="editScoreSubmit" :loading="editScoreLoading">{{ $t('golbal.btn_text_1') }}</el-button>
            <el-button color="#435764" @click="editScoreDialog = false" :loading="editScoreLoading">{{ $t('golbal.btn_text_3') }}</el-button>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { useRoute } from 'vue-router'

import QuickFilter from '@/components/QuickFilter.vue'

import AssignService from '@/api/assign'
import type { AssignInfo, AssignReport } from '@/types/assign'

import { useRoleStore } from '@/stores/role'

import { downloadCSV, formatLoginTime, goPage } from '@/utils/global'
import moment from 'moment'

import { useI18n } from 'vue-i18n'
import type { SupportedLocales } from '@/locales/i18n'
import type { MessageSchema } from '@/types/i18n'

interface FilterParams {
    lastName: string
    firstName: string
}

const route = useRoute()
const roleStore = useRoleStore()
const courseId = computed(() => Number(route.params.courseId))
const unitId = computed(() => Number(route.params.unitId))
const id = computed(() => Number(route.params.assignId))
const loading = ref(false)
const { t } = useI18n<{ message: MessageSchema }, SupportedLocales>()
function statusText(status: number) {
    switch (status) {
        case 1:
            return 'mod.assign.report.table_label_3_con_1'
        case 2:
            return 'mod.assign.report.table_label_3_con_2'
        case 3:
            return 'mod.assign.report.table_label_3_con_3'
        case 4:
            return 'mod.assign.report.table_label_3_con_4'
        default:
            return 'mod.assign.report.table_label_3_con_5'
    }
}

// 搜索
const type = ref()
const resetFilter = () => {
    type.value = undefined
}

// 姓氏和名字 筛选
const filters = ref<FilterParams>({
    lastName: 'all',
    firstName: 'all',
})
const handleFilterChange = (newFilters: FilterParams) => {
    filters.value = newFilters
    getAssignReportList()
}

// 分页器
const pagination = ref({
    page: 1,
    limit: 10,
    total: 10,
})

// 学生作业成绩表
const assignReportList = ref<AssignReport[]>([])
const checkedReport = ref<AssignReport[]>([])
function getAssignReportList() {
    loading.value = true
    const form = {
        last_initial: filters.value.lastName,
        first_initial: filters.value.firstName,
        page: pagination.value.page,
        limit: pagination.value.limit,
        type: type.value,
    }
    AssignService.list(courseId.value, form)
        .then(res => {
            assignReportList.value = res.list
            pagination.value.total = res.total
            pagination.value.page = res.page
            pagination.value.limit = res.limit
        })
        .finally(() => {
            loading.value = false
        })
}
const handleSelectionChange = (val: AssignReport[]) => {
    checkedReport.value = val
}

// 反思报告信息
const assignInfo = ref<AssignInfo>()
function getAssignInfo() {
    AssignService.getByCourseId(courseId.value).then(res => {
        assignInfo.value = res
    })
}

// 下载
const downloadLoading = ref(false)
const downloadHandle = () => {
    downloadLoading.value = true
    const form = {
        last_initial: filters.value.lastName,
        first_initial: filters.value.firstName,
        type: type.value,
    }
    AssignService.downloads(courseId.value, form)
        .then(res => {
            downloadCSV(res, t('mod.assign.report.btn_text_3_tip'))
        })
        .finally(() => {
            downloadLoading.value = false
        })
}

// 查看档案
const viewDialog = ref(false)
const viewFileHandle = (row: AssignReport) => {
    checkedReport.value = [row]
    viewDialog.value = true
}

// 准许延期
const lateDateDialog = ref(false)
const lateDate = ref<string>('')
const lateDateLoading = ref(false)
const lateDateHandle = (row: AssignReport[]) => {
    if (row.length) checkedReport.value = row

    lateDate.value = checkedReport.value[0].late_date
    lateDateDialog.value = true
}
const lateDateSubmit = () => {
    lateDateLoading.value = true
    const ids: number[] = checkedReport.value.map((item: AssignReport) => item.id)
    AssignService.delaySubmitToStudents(id.value, ids, moment(lateDate.value).format('YYYY-MM-DD HH:mm:ss'))
        .then(() => {
            lateDateDialog.value = false
            getAssignReportList()
        })
        .finally(() => {
            lateDateLoading.value = false
        })
}

// 查看成绩
const viewGradeHandle = (row: AssignReport) => {
    goPage(`/console/course/${courseId.value}/unit/${unitId.value}/assign/${id.value}/correct?studentId=${row.student_id}`)
}

// 将作業回復為草稿
const backDraftDialog = ref(false)
const backDraftLoading = ref(false)
const backDraftHandle = (row: AssignReport[]) => {
    if (row.length) checkedReport.value = row
    backDraftDialog.value = true
}
const backDraftSubmit = () => {
    backDraftLoading.value = true
    const ids: number[] = checkedReport.value.map((item: AssignReport) => item.student_id)
    AssignService.backDraftToStudents(id.value, ids)
        .then(() => {
            backDraftDialog.value = false
            getAssignReportList()
        })
        .finally(() => {
            backDraftLoading.value = false
        })
}

// 修改评分
const editScoreDialog = ref(false)
const editScore = ref({
    score: 0,
    teacher_comment: '',
})
const editScoreLoading = ref(false)
const editScoreHandle = (row: AssignReport[]) => {
    checkedReport.value = row
    editScoreDialog.value = true
}
const editScoreSubmit = () => {
    editScoreLoading.value = true
    const { student_id } = checkedReport.value[0]
    AssignService.updateByScore(id.value, student_id, editScore.value.score, editScore.value.teacher_comment)
        .then(() => {
            editScoreDialog.value = false
            editScore.value.score = 0
            editScore.value.teacher_comment = ''
            getAssignReportList()
        })
        .finally(() => {
            editScoreLoading.value = false
        })
}

onMounted(() => {
    getAssignInfo()
    getAssignReportList()
})
</script>

<style lang="less" scoped>
.pagination-box{
    justify-content: center;
    margin-top: 25px;
}
h2 {
    margin-bottom: 30px;
    font-size: 30px;
    font-weight: normal;
    line-height: 1.2;
    color: #000;
}

.activity-dates {
    margin-bottom: 6px;

    .date-p {
        color: #4c4c4c;
        line-height: 1.6;
        font-size: 15px;

        display: flex;
        align-items: center;
        gap: 10px;
    }
}

.tag-list {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    gap: 5px;
}

.search-form {
    margin-bottom: 40px;
    border: 1px solid #dee2e6;
    border-radius: 4px;
    padding: 15px;
    background-color: #f8f9fa;

    display: flex;
    flex-wrap: wrap;
    gap: 0 30px;

    .el-form-item {
        width: calc(50% - 15px);
    }

    .btn-list {
        margin-top: 0;
        justify-content: flex-end;
    }
}

.el-icon-list {
    display: flex;
    align-items: center;
    gap: 8px;

    .el-icon {
        cursor: pointer;
    }
}

.btn-list {
    margin-top: 30px;
    display: flex;
    justify-content: center;
    width: 100%;

    &.justify-end {
        margin-top: 0;
        margin-bottom: 15px;
        justify-content: flex-end;
    }
}

.file-upload-submission {
    padding: 15px;
    max-width: 450px;
    background-color: #e6e6e6;

    .file-time {
        margin-bottom: 20px;

        display: flex;
        align-items: center;
        justify-content: space-between;

        .file-name {
            color: #000;

            display: flex;
            align-items: center;
            gap: 6px;
        }
    }

    h4 {
        margin-bottom: 8px;
        color: #000;
        font-size: 20px;
        line-height: 1.2;
        font-weight: normal;
    }

    table {
        width: 100%;
        border: 1px solid #dee2e6;
        border-collapse: collapse;
        border-spacing: 0;

        tr {
            background-color: #f2f2f2;

            &:nth-child(2n) {
                background-color: #fff;
            }

            td {
                border: 1px solid #dee2e6;
                padding: 6px;
                color: #212529;
                font-size: 12px;
                line-height: 1.6;

                &:first-child {
                    color: #000;
                }
            }
        }
    }
}

.user-box {
    margin-bottom: 15px;
    width: 100%;

    &:last-child {
        margin-bottom: 0;
    }
}
</style>
